﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using Telerik.Windows.Controls.Charting;
using PersonalHealth.Data.Service;
using PersonalHealth.Data.IService;
using HealthManagement.Models;

namespace HealthManagement.Views
{
    /// <summary>
    /// Index.xaml 的交互逻辑
    /// </summary>
    public partial class Index : Page
    {
        IMeasureUserService ser = new MeasureUserService();
        public Index()
        {
            InitializeComponent();
            //rc.DefaultView.ChartLegend.Style = Application.Current.FindResource("CustomLegendItemStyle") as Style;
            //rc.DefaultView.ChartLegend.Foreground = Application.Current.FindResource("text") as Brush;
            rc.DefaultView.ChartLegend.Background = new SolidColorBrush(Colors.Transparent);
            rc.DefaultView.ChartLegend.BorderThickness = new Thickness(0);
            rc.DefaultView.ChartLegend.Header = "";
            //rc.DefaultView.ChartLegend.LegendItemStyle = Application.Current.FindResource("ChartLegendItemStyle") as Style;
            //rc.DefaultView.ChartArea.AxisX.Visibility = Visibility.Collapsed;
            //rc.DefaultView.ChartArea.AxisX.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            rc.DefaultView.ChartArea.AxisX.DefaultLabelFormat = "#VAL{yy年M月}";
            rc.DefaultView.ChartArea.AxisX.Step = 1;
            //rc.DefaultView.ChartArea.AxisY.AxisStyles.GridLineStyle = Application.Current.FindResource("YGridLineStyle") as Style;
            //rc.DefaultView.ChartArea.AxisY.AxisStyles.ItemLabelStyle = Application.Current.FindResource("XItemLabelStyle") as Style;
            rc.DefaultView.ChartArea.AxisY.ExtendDirection = AxisExtendDirection.Up;
            rc.DefaultView.ChartArea.AxisY.MinorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.StripLinesVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorTicksVisibility = Visibility.Collapsed;
            rc.DefaultView.ChartArea.AxisY.MajorGridLinesVisibility = Visibility.Visible;
            rc.DefaultView.ChartArea.AxisY.PlotAreaAxisVisibility = Visibility.Collapsed;



            InitTotalINfo();
            DataTable dt = ser.GetInvalidMeasuredUserList();
            InitInvalidMeasured(dt);

            //this.Loaded += new RoutedEventHandler(Index_Loaded);
        }

        private void InitTotalINfo()
        {
            DataSet dset = ser.GetMeasuredUserList();


            int[] totalCount = new int[5];
            int[] invalidCount = new int[5];
            int[] validCount = new int[5];

            List<MeasureData>[] lists = new List<MeasureData>[5];
            List<List<ChartValue>> values = new List<List<ChartValue>>();
            values.Add(new List<ChartValue>());
            values.Add(new List<ChartValue>());

            for (int i = 0; i < 5; i++)
            {
                lists[i] = dset.Tables[i].AsEnumerable().Select(c =>
                    new MeasureData
                    {
                        UserId = c.Field<int>("userid"),
                        UserName = c.Field<string>("username"),
                        MeasureType = c.Field<string>("measureType"),
                        MeasureDate = c.Field<string>("measureDate"),
                        MeasureValue = c.Field<decimal?>("measureValue"),
                        Max = c.Field<decimal?>("max"),
                        Min = c.Field<decimal?>("min")
                    }).ToList();

                totalCount[i] = lists[i].Select(c => c.UserId).Distinct().Count();
                invalidCount[i] = lists[i].Where(c => c.MeasureValue != null && (c.MeasureValue < c.Min || c.MeasureValue > c.Max))
                   .Select(c => c.UserId).Distinct().Count();
                validCount[i] = totalCount[i] - invalidCount[i];
                values[0].Add(new ChartValue() { Value = validCount[i], Time = DateTime.Now.AddMonths(-4 + i) });
                values[1].Add(new ChartValue() { Value = invalidCount[i], Time = DateTime.Now.AddMonths(-4 + i) });
            }

            runTotal.Text = string.Format("客户总数为：{0}人", totalCount[4]);
            runNormal.Text = string.Format("正常的有：{0}人", validCount[4]);
            runAlarm.Text = string.Format("异常的有：{0}人", invalidCount[4]);


            List<TestData> datas2 = new List<TestData>();
            datas2.Add(new TestData { Name = "正常数", Value = validCount[4] });
            datas2.Add(new TestData { Name = "异常数", Value = invalidCount[4] });
            rc1.ItemsSource = datas2;

            #region chart
            rc.SeriesMappings.Clear();
            rc.ItemsSource = null;
            rc.DefaultView.ChartArea.EnableAnimations = true;
            rc.DefaultView.ChartLegend.Header = "最近5个月数据对比";

            SeriesMapping mapping = new SeriesMapping();
            mapping.LegendLabel = "正常数";
            mapping.CollectionIndex = 0;
            SplineSeriesDefinition def = new SplineSeriesDefinition();
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
            rc.SeriesMappings.Add(mapping);

            mapping = new SeriesMapping();
            mapping.LegendLabel = "异常数";
            mapping.CollectionIndex = 1;
            def = new SplineSeriesDefinition();
            def.ItemLabelFormat = "0.#";
            def.ShowItemLabels = true;
            def.Appearance = new SeriesAppearanceSettings { Fill = Application.Current.FindResource("actual") as Brush };
            mapping.SeriesDefinition = def;
            mapping.ItemMappings.Add(new ItemMapping("Value", DataPointMember.YValue));
            mapping.ItemMappings.Add(new ItemMapping("Time", DataPointMember.XCategory));
            rc.SeriesMappings.Add(mapping);



            rc.ItemsSource = values;


            #endregion;
        }

        private void InitInvalidMeasured(DataTable table)
        {
            List<InvalidMeasuredUser> l = table.AsEnumerable().Select(c =>
                new InvalidMeasuredUser
                {
                    UserId = c.Field<int>("userid"),
                    UserName = c.Field<string>("username"),
                    Type = c.Field<string>("measureType"),
                    Date = c.Field<DateTime>("measureDate"),
                    Value = c.Field<double>("measureValue"),
                    Max = c.Field<double>("max"),
                    Min = c.Field<double>("min")
                }).ToList();

            List<InvalidMeasuredUser> q = (from i in l
                                           group i by new { UserID = i.UserId, Type = i.Type }
                                               into grp
                                               select new InvalidMeasuredUser
                                               {
                                                   UserId = grp.Key.UserID,
                                                   Type = grp.Key.Type,
                                                   Date = grp.Max(c => c.Date)
                                               }).ToList();

            List<InvalidMeasuredUser> list = new List<InvalidMeasuredUser>();
            foreach (var i in q)
            {
                list.Add(l.Single(c => c.UserId == i.UserId && c.Type == i.Type && c.Date == i.Date));
            }
            radGridView1.ItemsSource = list.Take(20);
        }
    }
    public class TestData
    {
        public string Name { get; set; }
        public DateTime Date
        {
            get;
            set;
        }
        public int Value { get; set; }

        public string Number { get; set; }
    }
}
